package com.bawei.yangzongcai___day2.MVCAcyivity;

import android.os.Handler;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

/**
 * create by ertu
 * create on 2021/7/27
 * description
 */
public class OkhttpMvc {
    public static OkhttpMvc okhttpMvc;
    public static Handler handler;
    public static OkHttpClient client;

    public static OkhttpMvc getOkhttpMvc()
    {
        if (okhttpMvc==null)
        {
            okhttpMvc=new OkhttpMvc();
        }
        return okhttpMvc;
    }


    public OkhttpMvc()
    {
        client = new OkHttpClient.Builder()
                .addInterceptor(new HttpLogingtion())
                .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                .writeTimeout(2, TimeUnit.MINUTES)
                .readTimeout(2, TimeUnit.MINUTES)
                .connectTimeout(2, TimeUnit.MINUTES)
                .build();
        handler = new Handler();
    }


    public void doGet(String sms, final MyCallBack myCallBack){
        client.newCall(new Request.Builder()
                .url(sms)
                .build())
                .enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (myCallBack!=null)
                {
                    myCallBack.fiad(e.getMessage());
                }
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                if (response.code() ==200)
                {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                               if (myCallBack!=null)
                               {
                                   myCallBack.suuess(response);
                               }
                        }
                    });
                }
                else
                {
                    if (myCallBack!=null)
                    {
                        myCallBack.fiad(response.message());
                    }
                }

            }
        });
    }


    public interface  MyCallBack
    {
        void suuess(Response response);
        void fiad(String fiai);
    }
}
